package org.cardoso.coyote.web.servlet;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.cardoso.coyote.persistence.Persistence;

public abstract class AbstractServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public AbstractServlet() {
		super();
	}

	@SuppressWarnings({ "rawtypes" })
	protected Persistence createPersistence(HttpServletRequest httpServletRequest, Class serviceClass) {
		return createPersistence(httpServletRequest, serviceClass, "default");
	}

	@SuppressWarnings({ "rawtypes" })
	protected Persistence createPersistence(HttpServletRequest httpServletRequest, Class serviceClass, String unitName) {
		try {
			EntityManager entityManager = (EntityManager) httpServletRequest.getAttribute(unitName);
			Object persistence = (Persistence) serviceClass.newInstance();
			((Persistence) persistence).setEntityManager(entityManager);
			return (Persistence) persistence;
		} catch (Throwable e) {
			e.printStackTrace();
			return null;
		}
	}

}